<?php

namespace App\Console\Commands\Wanggui;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Models\Common\ConfigModel;
use App\Models\Common\MapNationalStreetModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class ImportStreetData extends Command
{
    /**
     * The name and signature of the console command.
     * @var string
     */
    protected $signature = 'wanggui:import-street-data {--date=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入街道网规数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
//        $fileNames = [
//            '济南推荐区域.geojson',
//            '北京市推荐选址区域.geojson',
//            '广州推荐区域.geojson',
//            '厦门街道网规.geojson',
//            '上海推荐区域网规.geojson',
//            '深圳推荐区域.geojson',
//            '苏州杭州推荐区域.geojson',
//            '无锡推荐区域.geojson',
//            '宁波街道网规.geojson',
//            '武汉街道网规.geojson',
//            '绍兴街道网规.geojson',
//        ];
//
//        foreach ($fileNames as $name) {
//            $this->do(file_get_contents('https://file.51kuafu.com/wanggui/' . urlencode($name)));
//        }
        $streetGeoJsonArr = json_decode(
            ConfigModel::query()
                ->where('module', ConfigModel::MODULE_WANGGUI)
                ->where('name', ConfigModel::NAME_STREET_GEO_JSON)
                ->value('value'),
            true
        );

        //获得最新的key
        $prefix = [];
        foreach (array_keys($streetGeoJsonArr) as $streetKey) {
            if (strpos($streetKey, Carbon::now()->toDateString())) {
                $prefix[] = (int)$streetKey;
            }
        }
        //要处理的key的列表
        $date = $this->option('date') ?: (max($prefix) . ':' . Carbon::now()->toDateString());
        foreach ($streetGeoJsonArr as $dateKey => $streetList) {
            if ($dateKey == $date) {
                foreach ($streetList as $street) {
                    if (strlen($street['url']) <= 1) {
                        continue 2;
                    }
                    $this->info($street['name'] . '----->>>>>>>>>>>即将导入');
                    $this->do(file_get_contents($street['url']));
                }
            }

        }
    }

    private int $num = 1;

    private function do(string $gJson)
    {
        $gArr = json_decode($gJson, true);

        foreach ($gArr['features'] as  $feature) {
            if (is_array($feature['geometry']['coordinates'][0][0][0])) {
                $coordinates = $feature['geometry']['coordinates'][0][0];
            } elseif (is_array($feature['geometry']['coordinates'][0][0])) {
                $coordinates = $feature['geometry']['coordinates'][0];
            } else {
                dd("coordinates error", $feature);
            }

            if (isset($feature['properties']['rank'])) {

                $rank = $feature['properties']['rank'];
                switch ($rank) {
                    case 'S':
                        $grade = ProgrammingEnum::GRADE_S;
                        break;
                    case 'A':
                        $grade = ProgrammingEnum::GRADE_A;
                        break;
                    case 'B':
                        $grade = ProgrammingEnum::GRADE_B;
                        break;
                    case 'C':
                        $grade = ProgrammingEnum::GRADE_C;
                        break;
                    case 'D':
                        $grade = ProgrammingEnum::GRADE_D;
                        break;
                    default:
                        $grade = 0;
                        break;
                }


            } elseif (isset($feature['properties']['id'])) {
                $grade = $feature['properties']['id'] + 2;

            } elseif (isset($feature['properties']['priority'])) {
                $grade = $feature['properties']['priority'];

                if ($grade == 1) {
                    $grade = ProgrammingEnum::GRADE_S;;
                } elseif ($grade == 2) {
                    $grade = ProgrammingEnum::GRADE_A;
                } elseif ($grade == 3) {
                    $grade = ProgrammingEnum::GRADE_B;
                } elseif ($grade == 4) {
                    $grade = ProgrammingEnum::GRADE_C;
                } else {
                    $grade = 0;
                }

            } else {

                if ($feature['properties']['id'] === null) {
                    $grade = 0;
                } else {
                    dd("grade error", $feature);
                }
            }

            // 取中心点
            $lng = $lat = 0;
            foreach ($coordinates as $v) {
                $lng += $v[0];
                $lat += $v[1];
            }

            $lng /= count($coordinates);
            $lat /= count($coordinates);

            $check = MapNationalStreetModel::query()->updateOrCreate(['lat' => $lat, 'lng' => $lng],
                ['grade' => $grade, 'coords' => json_encode($coordinates)]);
            if ($check->name) {
                $this->info("repeat {$lat}-{$lng}");
                continue;
            }

            $key = WangGuiCityByPower::getRandomAmapKey();
            $areaRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                           ->get(config('area.geocodeRegeo'), [
                               'key'      => $key,
                               'location' => $lng . ',' . $lat,
                           ])
                           ->json();

            if ($areaRes['status'] != 1) {
                continue;
            }

            $addressComponent = $areaRes['regeocode']['addressComponent'];
            $city             = empty($addressComponent['city']) ? $addressComponent['province'] : $addressComponent['city'];
            $province         = $addressComponent['province'];
            $district         = empty($addressComponent['district']) ? $addressComponent['city'] : $addressComponent['district'];
            $street           = $addressComponent['township'] ?: '';
            $address          = $areaRes['regeocode']['formatted_address'];

            if (!$city) {
                if ($province == '北京市') {
                    $city = '北京市';
                } elseif ($province == '上海市') {
                    $city = '上海市';
                }
            }

            $insertData = [
                'wgNumber' => 'JD55' . str_pad($check->id, 6, '0', STR_PAD_LEFT),
                'name'     => $street,
                'status'   => 0,
                'grade'    => $grade,
                'province' => $province,
                'city'     => $city,
                'district' => $district,
                'address'  => $address,
                'lat'      => $lat,
                'lng'      => $lng,
            ];

            dump($insertData);

            $check->update($insertData);

            $this->num++;
        }
    }
}
